using System.Threading.Tasks;
using UnityEngine;

namespace EntityKit.Runtime
{
    /// <summary>
    /// JSON数据序列化器
    /// </summary>
    public class JsonDataSerializer : IDataSerializer
    {
        /// <summary>
        /// 序列化对象为JSON字符串
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>JSON字符串</returns>
        public string Serialize(object obj) 
        {
            try 
            {
                return JsonMapper.ToJson(obj);
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"序列化失败 {ex.Message}");
            }
        }

        /// <summary>
        /// 异步序列化对象为JSON字符串
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>JSON字符串</returns>
        public async Task<string> SerializeAsync(object obj)
        {
            // 序列化通常是CPU操作，使用Task.Run避免阻塞主线程
            return await Task.Run(() => Serialize(obj));
        }

        /// <summary>
        /// 从JSON字符串反序列化对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="data">JSON数据</param>
        /// <returns>反序列化的对象</returns>
        public T Deserialize<T>(string data) 
        {
            try 
            {
                return JsonMapper.ToObject<T>(data);
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"JSON反序列化失败 {ex.Message}");
            }
        }

        /// <summary>
        /// 异步从JSON字符串反序列化对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="data">JSON数据</param>
        /// <returns>反序列化的对象</returns>
        public async Task<T> DeserializeAsync<T>(string data)
        {
            // 反序列化通常是CPU操作，使用Task.Run避免阻塞主线程
            return await Task.Run(() => Deserialize<T>(data));
        }
    }
}